import time
from threading import Thread, RLock

# 让抢夺的多个资源，使用1个递归锁进行多次锁定
chopsticks_lock = noodle_lock = RLock()


def eat1(name):
    """先抢到面条，再抢到筷子"""
    noodle_lock.acquire()
    print(f"{name}抢到了面条")
    chopsticks_lock.acquire()
    print(f"{name}抢到了筷子")
    time.sleep(0.1)
    print(f"{name}吃面")
    chopsticks_lock.release()
    noodle_lock.release()


def eat2(name):
    """先抢到筷子，再抢到面条"""
    chopsticks_lock.acquire()
    print(f"{name}抢到了筷子")
    noodle_lock.acquire()
    print(f"{name}抢到了面条")
    print(f"{name}吃面")
    time.sleep(0.1)
    noodle_lock.release()
    chopsticks_lock.release()


if __name__ == '__main__':
    for name in ["小白", "小明", "小红", "小胡"]:
        Thread(target=eat1, args=(name,)).start()
        Thread(target=eat2, args=(name,)).start()